package com.geekgo.callablefuture;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 *
 * @author HeHaoyang
 * @version 2016/6/12 18:23
 */
public class FileCounter implements Callable<Integer>{
    private File directory;
    private String keyword;
    private int count;

    public FileCounter(File directory, String keyword) {
        this.directory = directory;
        this.keyword = keyword;
    }

    @Override
    public Integer call() throws Exception {
        count = 0;
        try {
            File[] files = directory.listFiles();
            ArrayList<FutureTask> taskList = new ArrayList<FutureTask>();
            for(File file:files) {
                if(file.isDirectory()) {
                    FileCounter fileCounter = new FileCounter(file, keyword);
                    FutureTask<Integer> task = new FutureTask<Integer>(fileCounter);
                    taskList.add(task);
                    Thread t = new Thread(task);
                    t.start();
                } else {
                    boolean isHave = this.isHaveKeywordInFile(file);
                    if(isHave)  count++;
                }
            }

            for(FutureTask<Integer> futureTask:taskList) {
                count+= futureTask.get();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return count;
    }

    private boolean isHaveKeywordInFile(File file) {
        boolean isHave = false;
        Scanner in = null;
        FileInputStream inputStream = null;

        try {
            inputStream = new FileInputStream(file);
            in = new Scanner(inputStream);

            while(in.hasNextLine()) {
                String line = in.nextLine();
                if(line.contains(keyword)) {
                    isHave = true;
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(in != null) {
                in.close();
            }

        }

        return isHave;
    }
}
